package com.touchstone.cloudpacs.common.configuration;

import com.touchstone.cloudpacs.common.interceptor.OnlineInterceptor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.*;

/**
 * @Description: 跨域配置，拦截器配置, 并且放开对swagger的拦截
 * @Author: hunter
 * @Date:2019-07-10 16:20
 */
@Configuration
public class MvcConfig extends WebMvcConfigurationSupport {

    /**
     * 配置跨域
     * @return
     */
    private CorsConfiguration corsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //TODO 配置请求跨域的域名
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsFilter(source);
    }
    /**
     * 不拦截的api
     */
    private static final String[] EXCLUDE_API = {"/", "/login", "/user/login", "/log/**", "/test/**"};

    /**
     * 不拦截的静态资源路径
     */
    private static final String[] EXCLUDE_PATHS = {"/css/**", "/fonts/**", "/js/**", "/images/**",
            "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**"};


    /**
     * 注册拦截器
     *
     * @param registry
     * @return
     * @throws：
     * @createUserName: hunter
     * @createTime: 2019/7/24 23:22
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getOnlineInterceptor()).addPathPatterns("/**").excludePathPatterns(ArrayUtils.addAll(EXCLUDE_API, EXCLUDE_PATHS));
        super.addInterceptors(registry);
    }

    @Bean
    public OnlineInterceptor getOnlineInterceptor() {
        return new OnlineInterceptor();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }


}
